<?php
/**
 * @title 35. 搜索插入位置 - 二分查找简化
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer
     */
    function searchInsert($nums, $target) {
        /**
         * @since 2020-08-14 左右指针
         */
        $left = 0;
        $right = count($nums)-1;

        /**
         * @since 2020-08-15 上限
         */
        if($target>$nums[$right]){
            return $right+1;
        }

        /**
         * @since 2020-08-14 二分查找
         * @since 2020-08-15 nums[left] < target <= nums[right]
         */
        while($left<$right){
            $mid = ($left+$right)>>1;
            $val = $nums[$mid];

            if($target <= $val){
                $right = $mid;
            } else {
                /**
                 * @since 2020-08-14 target>val
                 */
                $left = $mid+1;
            }
        }

        /**
         * @return
         */
        return $left;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.17_2.php
 */
$datas = [
    [[1,3,5,6], 5],
    // [[1,3,5,6], 2],
    [[1,3,5,6], 7],
    // [[1,3,5,6], 0],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->searchInsert($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
